package com.example.leetdemo.process;

public class Solution306 {

    public static void main(String[] args) {
        Solution306 solution306 = new Solution306();
        System.err.println(solution306.isAdditiveNumber("198019823962564496061525024856111111"));
    }

    public boolean isAdditiveNumber(String num) {
        if (num.length() < 3) {
            return false;
        }
        for (int i = 0; i < num.length() - 2; i++) {
            if (check(0, i + 1, i + 2, num)) {
                return true;
            }
        }
        return false;
    }

    private boolean check(Integer index1, Integer index2, Integer index3, String str) {
        if (index3 == str.length()) {
            return false;
        }
        Long num1 = Long.parseLong(str.substring(index1, index2));
        Long num2 = Long.parseLong(str.substring(index2, index3));
        String num3 = String.valueOf(num1 + num2);
        if (String.valueOf(num1).length() != index2 - index1 || String.valueOf(num2).length() != index3 - index2) {

        } else if (str.substring(index3, Math.min(str.length(), index3 + num3.length())).equals(num3)) {
            if (str.length() == index3 + num3.length()) {
                return true;
            }
            if (check(index2, index3, index3 + num3.length(), str)) {
                return true;
            }
        }
        int i = index3;
        if (check(index1, index2, i + 1, str)) {
            return true;
        }
        if (check(index1, index2 + 1, index2 + 2, str)) {
            return true;
        }
        return false;
    }
}
